package com.sheyu.mall.product.service.category.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.sheyu.common.exception.CategoryException;
import com.sheyu.mall.product.dao.attr.AttrDao;
import com.sheyu.mall.product.dao.attr.AttrGroupDao;
import com.sheyu.mall.product.dao.category.CategoryBrandRelationDao;
import com.sheyu.mall.product.dao.sku.SkuInfoDao;
import com.sheyu.mall.product.dao.spu.SpuInfoDao;
import com.sheyu.mall.product.service.category.CategoryBrandRelationService;
import com.sheyu.mall.product.service.category.vo.Catelog2Vo;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sheyu.common.utils.PageUtils;
import com.sheyu.common.utils.Query;

import com.sheyu.mall.product.dao.category.CategoryDao;
import com.sheyu.mall.product.entity.category.CategoryEntity;
import com.sheyu.mall.product.service.category.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private CategoryBrandRelationDao categoryBrandRelationDao;

    @Autowired
    private AttrDao attrDao;

    @Autowired
    private SkuInfoDao skuInfoDao;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private SpuInfoDao spuInfoDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 后台的前端页面显示分类目录
     * @return
     */
    @Override
    public List<CategoryEntity> getAllCategories() {
        //获取所有的分类目录
        List<CategoryEntity> entities = baseMapper.selectList(null);
//        List<CategoryEntity> entities = baseMapper.selectListBySQL();
        //获取一级分类目录
        List<CategoryEntity> entityMenus = entities.stream().filter(categoryEntity ->
            categoryEntity.getParentCid()==0
        ).map((categoryEntity) ->{
            categoryEntity.setChildren(getChildrens(categoryEntity,entities));
            return categoryEntity;
        }).collect(Collectors.toList());
        return entityMenus;
    }

    /**
     * 根据catId得到子节点
     * @param root
     * @param allEntities
     * @return
     */
    public List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> allEntities){
        List<CategoryEntity> childrenMenus = allEntities.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map((categoryEntity)->{
            categoryEntity.setChildren(getChildrens(categoryEntity,allEntities));
            return categoryEntity;
        }).collect(Collectors.toList());
        return childrenMenus;
    }

    /**
     * 删除分类id，由于category_id在pms_attr、pms_sku_info、pms_attr、pms_attr_group、pms_spu_id、pms_sku_id等数据表存在对应的信息
     * @param catIds
     */
    @Override
    public void removeCategoryByIds(List<Long> catIds) {
        //涉及
//        baseMapper.deleteBatchIdsBySQL(catIds);

        Long existCatelogIdInAttr = 0L;
        Long existCatelogIdInSkuInfo = 0L;
        Long existCatelogIdInBrand = 0L;
        Long existCatelogIdInSpuInfo = 0L;
        List<Long> needRemoveCatelogIds = new ArrayList<>();
        for (int i = 0; i < catIds.size(); i++) {
            existCatelogIdInSpuInfo = spuInfoDao.selectByCatIdBySQL(catIds.get(i));
            existCatelogIdInAttr = attrDao.selectByCateIdBySQL(catIds.get(i));
            existCatelogIdInBrand = categoryBrandRelationDao.selectByCatIdBySQL(catIds.get(i));
            existCatelogIdInSkuInfo = skuInfoDao.selectByCatIdBySQL(catIds.get(i));
            if (existCatelogIdInAttr==0&&existCatelogIdInBrand==0&&existCatelogIdInSkuInfo==0
                    &&existCatelogIdInSpuInfo==0){
                needRemoveCatelogIds.add(catIds.get(i));
            }
        }
//        baseMapper.deleteBatchIds(needRemoveCatelogIds);
        baseMapper.deleteBatchIds(needRemoveCatelogIds);
    }

    /**
     *
     * @param catelogId
     * @return
     */
    @Override
    public Long[] categoryPath(Long catelogId) {
        List<Long> categoryEntities = new ArrayList<>();
        categoryEntities = findParentCategory(catelogId,categoryEntities);
        return categoryEntities.toArray(new Long[categoryEntities.size()]);
    }

    public List<Long> findParentCategory(Long catelogId,List<Long> categoryEntities){
        categoryEntities.add(catelogId);
        CategoryEntity categoryEntity = this.getById(catelogId);
        if (categoryEntity.getParentCid()!=0){
            findParentCategory(categoryEntity.getParentCid(),categoryEntities);
        }
        Collections.reverse(categoryEntities);
        return categoryEntities;
    }


    //@CacheEvict(value = "category",key="'getLevel1Categorys'")
    /**
     *
     * 1、清除多个缓存
     * @Caching(evict = {
            @CacheEvict(value = "category",key="'getLevel1Categorys'"),
            @CacheEvict(value = "category",key="'getCatalogJson'")
       })
     * 2、指定删除某个分区下的所有数据@CacheEvict(value = "category",allEntries = true)
     * 3、存储同一类型的数据，都可以指定成同一分区，分区名默认是缓存的前缀
     */
    @CacheEvict(value = "category",allEntries = true)
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        String categoryName = category.getName();
        if(StringUtils.isNotBlank(categoryName)){
            categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());

            //TODO 更新其他的关联
        }
    }

    /**
     * 4、Spring-Cache的不足之处：
     *      1）、读模式
     *           缓存穿透：查询一个null数据。解决方案：缓存空数据
     *           缓存击穿：大量并发进来同时查询一个正好过期的数据。解决方案：加锁 ? 默认是无加锁的;使用sync = true来解决击穿问题
     *           缓存雪崩：大量的key同时过期。解决：加随机时间。加上过期时间
     *       2)、写模式：（缓存与数据库一致）
     *           1）、读写加锁。
     *           2）、引入Canal,感知到MySQL的更新去更新Redis
     *           3）、读多写多，直接去数据库查询就行
     *
     *       总结：
     *           常规数据（读多写少，即时性，一致性要求不高的数据，完全可以使用Spring-Cache）：写模式(只要缓存的数据有过期时间就足够了)
     *           特殊数据：特殊设计
     *
     *       原理：
     *           CacheManager(RedisCacheManager)->Cache(RedisCache)->Cache负责缓存的读写
     * @return
     */
    @Cacheable(value = {"category"},key = "#root.method.name",sync = true)
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        System.out.println("获取getLevel1Categorys结果");
        List<CategoryEntity> categoryEntities = this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid",0));
//        List<CategoryEntity> categoryEntities1 = baseMapper.selectListByParentCidBySQL();
        return categoryEntities;
    }

    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        //给缓存中放json字符串，拿出的json字符串，反序列为能用的对象

        /**
         * 1、空结果缓存：解决缓存穿透问题
         * 2、设置过期时间(加随机值)：解决缓存雪崩
         * 3、加锁：解决缓存击穿问题
         */

        //1、加入缓存逻辑,缓存中存的数据是json字符串
        //JSON跨语言。跨平台兼容。
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        String catalogJson = ops.get("catalogJson");
        if (org.springframework.util.StringUtils.isEmpty(catalogJson)) {
            System.out.println("缓存不命中...查询数据库...");
            //2、缓存中没有数据，查询数据库
            Map<String, List<Catelog2Vo>> catalogJsonFromDb = getCatalogJsonWithRedissonLock();

            return catalogJsonFromDb;
        }

        System.out.println("缓存命中...直接返回...");
        //转为指定的对象
        Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJson,new TypeReference<Map<String, List<Catelog2Vo>>>(){});

        return result;
    }

    /**
     * redisson分布式锁
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonWithRedissonLock() {
        String uuid = UUID.randomUUID().toString();
        RLock getCatalogJson = redissonClient.getLock("getCatalogJson");
        getCatalogJson.lock();
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("getCatalogJson-lock");
        RLock rLock = readWriteLock.readLock();
        try{   //阻塞式加锁
            System.out.println("获取分布式锁成功。。。。");
            rLock.lock();
            //设置过期时间,加锁与设置过期时间必须是原子操作
            Map<String, List<Catelog2Vo>> catalogJson = getCatalogJsonFromDb();
            return catalogJson;
        }finally {
            rLock.unlock();
        }
    }
    /**
     *  redis setnx锁
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonWithRedisLock() {
        String uuid = UUID.randomUUID().toString();
        boolean lock = redisTemplate.opsForValue().setIfAbsent("lock",uuid,300,TimeUnit.SECONDS);
        if (lock){
            System.out.println("获取分布式锁成功。。。。");
            //设置过期时间,加锁与设置过期时间必须是原子操作
            Map<String, List<Catelog2Vo>> catalogJson;
            try{
                catalogJson = getCatalogJsonFromDb();
            }finally {
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";

                //删除锁
                redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), uuid);

            }

            //获取解锁值与删除锁操作必须是原子操作
//            String lockValue = redisTemplate.opsForValue().get("lock");
//            if (lockValue.equals(uuid)){
//                redisTemplate.delete("lock");
//            }
            return catalogJson;
        }else{
            System.out.println("获取分布式锁失败，等待重试。。。。。。");
            return getCatalogJson();
        }
    }
    /**
     * 本地锁 先从redis缓存读取数据，若不存在，则从数据库读取数据
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonWithLocalLock() {
        synchronized (this){
            return getCatalogJsonFromDb();
        }
    }

    /**
     * 从数据库获取分类数据
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDb() {
        String catelogJson = redisTemplate.opsForValue().get("catalogJson");
        if (!StringUtils.isBlank(catelogJson)) {
            return JSON.parseObject(catelogJson,new TypeReference<Map<String, List<Catelog2Vo>>>(){});
        }

        //获取所有的分类目录
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);

        List<CategoryEntity> category1LevelEntities = categoryEntities.stream().filter(categoryEntity -> {
            return  categoryEntity.getParentCid()==0;
        }).collect(Collectors.toList());

        Map<String, List<Catelog2Vo>> cataJson = category1LevelEntities.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            List<CategoryEntity> category2LevelEntities = getChidrenNode(v.getCatId(),categoryEntities);
            List<Catelog2Vo> catelog2Vos = null;
            if (category2LevelEntities != null) {
                catelog2Vos = category2LevelEntities.stream().map(level2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, level2.getCatId().toString(), level2.getName());
                    List<CategoryEntity> category3LevelEntities = getChidrenNode(level2.getCatId(),categoryEntities);
                    if (category3LevelEntities != null) {
                        List<Catelog2Vo.Category3Vo> category3Vos = category3LevelEntities.stream().map(level3 -> {
                            Catelog2Vo.Category3Vo category3Vo = new Catelog2Vo.Category3Vo(level2.getCatId().toString(), level3.getCatId().toString(),
                                    level3.getName());
                            return category3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(category3Vos);
                    }else{
                        throw new CategoryException("三级分类不存在");
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }else{
                throw new CategoryException("二级分类不存在");
            }
            return catelog2Vos;
        }));
        String s = JSON.toJSONString(cataJson);
        redisTemplate.opsForValue().set("catalogJson",s);
        return cataJson;
    }

    public List<CategoryEntity> getChidrenNode(Long catId,List<CategoryEntity> categoryEntities){
        List<CategoryEntity> childrenCategoryEntities = categoryEntities.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid().equals(catId);
        }).collect(Collectors.toList());
        return childrenCategoryEntities;
    }

}
